import {Injectable} from "@angular/core";
import {Http, Headers} from "@angular/http";
import {App, NavController} from "ionic-angular";
import {UserLogin} from "../modules/app-user/user-login/user-login";
import {AppPopup} from "./popup";
@Injectable()
export class AppHttp{
    private navCtrl: NavController;
    private headers = new Headers({'Content-Type': 'application/json'});

    constructor(private http: Http,
                private popup: AppPopup,
                private app: App) {
        this.navCtrl = app.getActiveNav();
    }

    //todo unknown function
    getData(url: string): Promise<any> {
        return this.http
            .get(url)
            .timeout(2000)
            .toPromise()
            .then(response => response.json())
            .catch(err => {
                return Promise.reject(err)
            })
    }

    post(url: string, param?: any): Promise<any> {
        return this.http
            .post(url, JSON.stringify(param),{headers: this.headers})
            .timeout(5000)
            .toPromise()
            .then(res => {
                let obj = res.json();
                if(obj.resultStatus == "success"){
                    return Promise.resolve(obj);
                } else {
                    return Promise.reject(obj);
                }
            })
            .catch(this.handleErr);
    }

    private handleErr(err):Promise<any>{
        if(err.status==503||err.status==0){
            return Promise.reject({"errorMassage":'应用服务器不可用！'});
        }
        if(err.status==404){
            return Promise.reject({"errorMassage":'您请求的资源不存在！'});
        }
        //防止服务器返回非约定格式的错误信息时，向用户弹出离奇错误提示
        if(err.errorMassage&&err.errorMassage!==""&&typeof err.errorMassage=='string'){
            return Promise.reject(err);
        }else if(err.message == "Timeout has occurred") {
            return Promise.reject({"errorMassage": "请求超时，请重试！"});
        }else {
            console.error('HxsmartHttp.post:服务器内部错误，原始响应如下：',err);
            return Promise.reject({"errorMassage":'服务器内部错误'});
        }
    }
}